#include "AllHeaders.h"

Lista::Lista()
{
	l = NULL;
	a = NULL;
	u = NULL;
}

Lista::~Lista()
{
}

bool Lista::Vazia()
{
	if(l == NULL)
		return true;

	return false;
}

Node* Lista::CriaNode(Node& _node)
{
	Node *nodePtr;
	nodePtr= new Node(_node);

	nodePtr->SetLeft(NULL);
	nodePtr->SetRight(NULL);

	return nodePtr;
}

bool Lista::Inserir(Node* _node)
{
	Node *nodePtr;

	if(Vazia())
	{
		l = CriaNode(*_node);
		a = l;
		u = l;
		return true;
	}
	else
	{
		nodePtr = CriaNode(*_node);

		nodePtr -> SetRight(l);
		l -> SetLeft(nodePtr);
		nodePtr ->SetLeft(NULL);
		l = nodePtr;

		return true;
	}

	return false;
}

bool Lista::Retirar(Node* _node)
{
	Node *nodePtr, _temp, _a;

	nodePtr = new Node();
	_temp = *_node;
	
	if (!Vazia())
	{
		if (BuscarPrimeiro(nodePtr))
		{
			//nodePtr = l;

			if (*nodePtr == _temp)
			{
				_temp = *nodePtr;
				*_node = _temp;

				nodePtr = l;
				l = l->GetRight();

				a = l;
				u = l;

				delete nodePtr;
				return true;
			}
			else
			{
				BuscarPrimeiro(nodePtr);
				while (BuscarProximo(nodePtr))
				{
					if (*nodePtr == _temp)
					{
						 _temp = *nodePtr;
						 *_node = _temp;

						 if (a->GetRight() == NULL)
						 {
							nodePtr = a->GetLeft();
							nodePtr->SetRight(NULL);
							
						 }
						 else
						 {
							nodePtr = a->GetLeft();
							nodePtr->SetRight(a->GetRight());
							nodePtr = nodePtr->GetRight();
							nodePtr->SetLeft(a->GetLeft());
						 }

						nodePtr = a;
						a = l;
						u = l;

						delete nodePtr;
						return true;
					}

				}
			}

		}

	}

	return false;
}

bool Lista::BuscarPrimeiro(Node* _node)
{
	Node temp;
	
	if (!Vazia())
	{
		a = l;
		temp = *a;
		*_node = temp;
		return true;
	}

	return false;
}

bool Lista::BuscarProximo(Node* _node)
{
	Node temp;

	if (a != NULL)
	{
		 if (a->GetRight() != NULL)
		{
			a = a->GetRight();
			temp = *a;
			*_node = temp;
			return true;
		}
	}

	return false;
}